package zl.applet.oldsnakey;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

//排行榜类、序列化玩家信息
public class Charts 
{
	//保存玩家的集合
	private ArrayList<Player> allPlayer = new ArrayList<Player>();

	//只读属性
	public ArrayList<Player> getAllPlayer()
	{
		return this.allPlayer;
	}
	
	//添加玩家
	public void add(Player p)
	{
		if(p == null)
			return;
		for(int i = 0; i < this.allPlayer.size(); i++)
		{
			//如果玩家存在、则删除旧记录
			if(this.allPlayer.get(i).getName().equals(p.getName()))
				this.allPlayer.remove(i);
		}
		//添加玩家
		this.allPlayer.add(p);
	}

	@SuppressWarnings("unchecked")    //取消显示警告
	//加载序列化信息
	public void load() throws Exception
	{
		File obj = new File("D:" + File.separator + "Charts.bin");   //实例化文件类型
		if(!obj.exists())   //判断文件是否存在
			return;
		ObjectInputStream ois = null;   //声明输入流
		try
		{
			ois = new ObjectInputStream(new FileInputStream(obj));  //根据文件实例化输入流
			this.allPlayer = (ArrayList<Player>)ois.readObject();  //读取文件
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				ois.close();  //关闭输入流
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}	
		}
	}

	//保存信息
	public void save() throws Exception
	{	
		//Charts.class.getResource("/").toURI().getPath()
		File obj = new File("D:" + File.separator + "Charts.bin");
		ObjectOutputStream oos =  null;
		try
		{
			oos = new ObjectOutputStream(new FileOutputStream(obj));
			while(this.allPlayer.size() >= 10)
				this.allPlayer.remove(10);   //只保存十条记录
			oos.writeObject(this.allPlayer);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				oos.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}